﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using FileSquirrel.Logic;
using FileSquirrel.Logic.XSD;
using FSquirrel.Properties;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using FSquirrel.Design;
using GalaSoft.MvvmLight.Messaging;
using System.Linq;
using System;
using System.Collections;
using FSquirrel.Messages;

namespace FSquirrel.ViewModel
{
    public class RequestViewModel : ViewModelBase
    {

        public RequestViewModel()
        {
            Messenger.Default.Register<RequestMessage>(this, ProcessRequest);

            CheckAllCommand = new RelayCommand<object>(ChangeFilteredChekcAll);
            SpacebarDataGridCommand = new RelayCommand<object>(CheckboxFilterItemChange);

            _Indexer.RequestFilesName = string.Format("{0}_RequestFrom_{0}", Settings.Default.LibraryName);

        }


        #region Properties

        //RelayCommands
        public RelayCommand<object> CheckAllCommand { get; private set; }
        public RelayCommand<object> SpacebarDataGridCommand { get; private set; }


        public const string TotalSizePropertyName = "TotalSize";
        public const string RequestListCollectionPropertyName = "RequestListCollection";
        public const string AllCheckSelectionPropertyName = "AllCheckSelection";


        private bool _allcheckselection = false;
        private ObservableCollection<FileRowModel> _requestlistcollection = new ObservableCollection<FileRowModel>();
        private int _totalsize;



        public bool AllCheckSelection
        {
            get
            {
                return _allcheckselection;
            }

            set
            {
                if (_allcheckselection == value)
                {
                    return;
                }

                RaisePropertyChanging(AllCheckSelectionPropertyName);
                _allcheckselection = value;
                RaisePropertyChanged(AllCheckSelectionPropertyName);
            }
        }

        public ObservableCollection<FileRowModel> RequestListCollection
        {
            get
            {
                return _requestlistcollection;
            }

            set
            {
                if (_requestlistcollection == value)
                {
                    return;
                }

                RaisePropertyChanging(RequestListCollectionPropertyName);
                _requestlistcollection = value;
                RaisePropertyChanged(RequestListCollectionPropertyName);
            }
        }


        public int TotalSize
        {
            get
            {
                if (RequestListCollection != null)
                {
                    return (from dr in RequestListCollection.Cast<FileRowModel>()
                            select dr.Size).Sum();
                }
                return 0;
            }


        }
        #endregion

        #region Methods

        private void CheckboxFilterItemChange(object sender)
        {
            IList items = (IList)sender;
            var collection = items.Cast<FileRowModel>();

            //If any current are select and more than to be selected then change all to true
            int _countselected = collection.Count(x => x.IsRequested);

            bool _partialselect = items.Count > _countselected;


            foreach (FileRowModel item in collection)
            {
                if (_partialselect)
                {
                    item.IsRequested = true;
                }
                else
                {
                    item.IsRequested = !item.IsRequested;
                }
            }
        }

        private void ChangeFilteredChekcAll(object sender)
        {
            if (sender.ToString().Equals("Clear"))
            {
                if (AllCheckSelection)
                {
                    AllCheckSelection = false;
                }

            }
            else
            {
                RequestListCollection.Cast<FileRowModel>().ToList().ForEach(x => x.IsRequested = Convert.ToBoolean(sender));

                RaisePropertyChanged(RequestListCollectionPropertyName);
            }
        }


        private void ProcessRequest(RequestMessage message)
        {

            IEnumerable<FileRowModel> Rlist = message.requestlist;


            switch (message.RAction)
            {
                case RequestAction.Add:
                    var newItems = Rlist.Where(x => !RequestListCollection.Any(y => x.Name == y.Name));

                    foreach (var item in newItems)
                    {
                        RequestListCollection.Add(item);
                    }
                    RequestListCollection.Cast<FileRowModel>().ToList().ForEach(x => x.IsSelected = false);

                    break;
                case RequestAction.Clear:


                    var c = RequestListCollection.Where(x => x.IsRequested).ToList<FileRowModel>();

                    foreach (FileRowModel item in c)
                    {
                        item.IsRequested = false;
                        RequestListCollection.Remove(item);
                    }


                    break;
                default:
                    break;
            }



            RaisePropertyChanged(RequestListCollectionPropertyName);
            RaisePropertyChanged(TotalSizePropertyName);

            ProcessRequestFileChanges();
        }

        private void ProcessRequestFileChanges()
        {


            Reader.GlobalRequestLibrary = new LibraryDataSet();
            string requestLib = ((LibraryDataSet.LibraryRow)Reader.GlobalLibrary.Library.Rows[0]).Library_Id;
            Reader.GlobalRequestLibrary.Library.AddLibraryRow(requestLib);



            foreach (FileRowModel requestitem in RequestListCollection)
            {

                Reader.GlobalRequestLibrary.RequestList.AddRequestListRow((LibraryDataSet.LibraryRow)Reader.GlobalRequestLibrary.Library.Rows[0], requestitem.Path, requestitem.Name, requestitem.Category, requestitem.Size);
            }

            _Indexer.SaveRequest();
        }
        #endregion

        private Indexer indexer;
        public Indexer _Indexer
        {
            get { return indexer ?? (indexer = new Indexer(Settings.Default.LibraryName, Settings.Default.LibraryDir)); }
        }
    }
}
